package server;

import classLoader.MyClassLoader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Mapper {

    private Integer port;
    private Host host;

    Mapper() throws FileNotFoundException {
        loadServerXml();
        parseAppBase();
    }

    /**
     * 解析App目录 存储 app应用，与目录明细
     * 1、获取web.xml
     * 2、缓存应用
     * 3、解析静态资源
     */
    private void parseAppBase() throws FileNotFoundException {
        if(host==null){
            return;
        }

        List<Context> list = new ArrayList<>();
        host.setContexts(list);

        File file = new File(host.getAppBase());
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                String appName = file1.getName();
                String demoPath = file1.getAbsolutePath();

//                加载解析相关的配置，web.xml
                Context c = loadServlet(appName,demoPath);
                list.add(c);
            }
        }
    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private Context loadServlet(String appName, String appPath) {
        SAXReader saxReader = new SAXReader();
        Context context = new Context();
        context.setName(appName);
        try {
            MyClassLoader myClassLoader = new MyClassLoader(appPath);
            String webxmlPath = appPath+"//web.xml";
            InputStream inputStream = new FileInputStream(webxmlPath);

            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                HttpServlet servlet = (HttpServlet) myClassLoader.findClass(servletClass).newInstance();
                context.getWrapper().put(urlPattern, servlet);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return context;
    }

    /**
     * 加载解析server.xml，初始化Server
     */
    private void loadServerXml() {
        InputStream resourceAsStream =
                this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> list = rootElement.selectNodes("//Service");
            for (int i = 0; i < list.size(); i++) {
                Element element =  list.get(i);

                Element connector = (Element) element.selectSingleNode("Connector");
                port = Integer.parseInt(connector.attributeValue("port"));

                Element engine = (Element) element.selectSingleNode("Engine");
                Element host1 = (Element) engine.selectSingleNode("Host");
                String name1 = host1.attributeValue("name");
                String appBase1 = host1.attributeValue("appBase");
                host = new Host(name1, appBase1);
                break;
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Host getHost() {
        return host;
    }

    public void setHost(Host host) {
        this.host = host;
    }
}
